<template>
  <div class="activity-add-container">
    <el-form ref="form" :model="activity_add_params" :rules="option.rules" label-width="80px">
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="activity_add_params.name"/>
      </el-form-item>
      <el-form-item label="活动类型" prop="type">
        <el-input v-model="activity_add_params.type"/>
      </el-form-item>
      <el-form-item label="活动简介" prop="disc">
        <el-input v-model="activity_add_params.disc" type="textarea"/>
      </el-form-item>
      <el-form-item label="服务时段" prop="timeRange">
        <el-date-picker
          type="datetimerange"
          v-model="activity_add_params.timeRange"
          value-format="yyyy-MM-DD hh:mm:ss"
          end-placeholder="请选择介绍时间"
          prefix-icon="el-icon-time"
          start-placeholder="选择开始时间"
          time-arrow-control
          clearable
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="收费情况" prop="isFree">
        <el-select v-model="option.isFree" placeholder="请选择活动是否收费">
          <el-option :value="0" label="收费"/>
          <el-option :value="1" label="免费"/>
        </el-select>
      </el-form-item>
      <el-form-item v-show="!option.isFree" label="费用(元)">
        <el-input-number
          v-model="activity_add_params.charge"
          :min="1"
          placeholder="费用"
        />
      </el-form-item>
      <el-form-item label="能否请假" prop="isCanLeave">
        <el-select v-model="activity_add_params.isCanLeave" placeholder="请选择活动能否请假">
          <el-option :value="1" label="是"/>
          <el-option :value="0" label="否"/>
        </el-select>
      </el-form-item>
      <el-form-item label="选择社团" prop="communityId">
        <el-cascader
          placeholder="请选择社团"
          v-model="activity_add_params.communityId"
          :props="communityID"
          clearable
        />
      </el-form-item>
      <el-form-item label="安排岗位">
        <el-row
          v-for="(options, index) in activity_add_params.jobList"
          :key="options.label"
          type="flex"
        >
          <el-col>
            <el-select v-model="options.jobId" placeholder="请选择岗位">
              <el-option
                v-for="item in option.jobList"
                :key="item.value"
                :disabled="activity_add_params.jobList.some(value=> value.jobId === item.value )"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col style="display: flex">
            <label style="width: 5em"> 招募人数: </label>
            <el-input-number
              v-model="options.jobNumber"
              :min="0"
            />
          </el-col>
          <el-col style="display: flex">
            <label style="width: 5em"> 可获分数: </label>
            <el-input-number
              v-model="options.jobScore"
              :min="0"
            />
          </el-col>
          <el-col>
            <i class="el-icon-plus icon-btn   bg-gradual-green"
               @click="handlePushJob(options)"
               v-show="index === activity_add_params.jobList.length - 1"
               style="user-select: none;cursor: pointer"
            />
            <i class="el-icon-minus icon-btn bg-gradual-red"
               @click="handlePopJob(index)"
               v-show="index !== activity_add_params.jobList.length - 1"
               style="user-select: none;cursor: pointer"

            />

          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="活动地点" prop="address">
        <b-map @confirm-location="confirmLocation"></b-map>
      </el-form-item>
      <el-form-item>
        <el-upload
          :before-remove="beforeRemove"
          :file-list="option.fileList"
          :http-request="handleUpload"
          :limit="1"
          :on-exceed="handleExceed"
          action
          class="upload-demo"
          list-type="picture-card"
          name="singleFile"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">最多上传一张活动标志</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="success" v-if="!isEdit" @click="toSubmit">立即发布</el-button>
        <el-button type="warning" v-else @click="toSubmitEdit">完成修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import moment from 'moment';

export default {
  components: {
    'b-map': () => import('../../components/map/bMap'),
  },
  async mounted() {
    // console.log(`this.$route-->`, this.$route);
    const info = this.$route.params;
    await this.handleGetJob();
    await this.handleSetDefault(info);
  },
  data() {
    return {
      isEdit: false,
      activity_add_params: {
        activityId: null,
        name: '',
        disc: '',
        timeRange: '',
        charge: 0,
        communityId: '',
        cover: '',
        type: '',
        jobList: [{
          jobId: null,
          jobNumber: null,
          jobScore: null,
        }],
        address: '',
        symbol: '',
        mobile: '',
        creater_name: '',
        isCanLeave: '',
      },
      communityID: {
        lazy: true,
        // 由于lazyLoad中的this指向会改变，所以提前指定this，便于使用Vue的this操控
        self: this,
        checkStrictly: true,
        async lazyLoad(node, resolve) {
          // 获取 当前社团的下一级信息
          const {
            level,
            value,
          } = node;
          if (level < 1) {
            const res = await this.self.$http.communityGetChildCommunity(0);
            console.log(res);
            const nodes = [];
            for (const each of res.data) {
              nodes.push({
                value: each.communityId,
                label: each.communityName,
                leaf: level >= 2,
              });
            }
            resolve(nodes);
          } else {
            const res = await this.self.$http.communityGetChildCommunity(value);
            const nodes = [];
            // console.log(res)
            for (const each of res.data) {
              nodes.push({
                value: each.communityId,
                label: each.communityName,
                leaf: level >= 2,
              });
            }
            resolve(nodes);
          }
        },
      },
      option: {
        jobList: [],
        isFree: 1,
        rules: {
          name: [{
            required: true,
            message: '请输入活动名称',
            trigger: 'blur',
          }],
          type: [{
            required: true,
            message: '请输入活动类型',
            trigger: 'blur',
          }],
          disc: [{
            required: true,
            message: '请输入活动描述',
            trigger: 'blur',
          }],
          address: [{
            required: true,
            message: '请选择活动地址',
            trigger: 'blur',
          }],
          timeRange: [{
            required: true,
            message: '请选择活动时间',
            trigger: 'blur',
          }],
        },
        fileList: [],
      },
    };
  },
  methods: {
    async handleGetJob() {
      const res = await this.$http.getJobAll();
      if (res.code !== 0) return null;
      const job = this.option.jobList;
      // 获得活动ID
      for (const {
        jobName,
        jobId
      } of res.data) {
        job.push({
          label: jobName,
          value: jobId,
        });
      }
    },
    handlePushJob(currentJob) {
      console.log(`currentJob-->`, currentJob);
      if (currentJob.jobId === null) return this.$message.warning('请不要留下空白');
      const form = this.activity_add_params;
      form.jobList.push({
        jobId: null,
        jobNumber: null,
        jobScore: null,
      });
    },
    handlePopJob(index) {
      const form = this.activity_add_params;
      form.jobList.splice(index, 1);
    },
    async toSubmitEdit() {
      const params = this.formatForm();
      let res;
      try {
        // 优先测试这个方法
        res = await this.$http.activityUpdate(params);
      } catch (e) {
        res = await this.$http.activityUpdatePost(params);
      }
      if (res.code !== 0) return null;
      this.$router.go(0);
    },
    formatForm() {
      const {
        isFree,
      } = this.option;
      const {
        activityId,
        jobList,
        address,
        timeRange,
        disc,
        charge,
        name,
        communityId,
        cover,
        type,
        isCanLeave,
      } = this.activity_add_params;
      console.log(isFree);

      let toUtcTime = (val) => {
        return this.$moment(val).format('YYYY-MM-DD hh:mm:ss');
      };
      let tmp = 0;
      for (let i in jobList) {
        tmp = jobList[i].jobNumber + tmp;
        if (jobList[i].jobId === null) {
          jobList.splice(i, 1);
        }
      }
      return {
        activityEntity: {
          activityId,
          activityAddress: address,
          activityDatetime: timeRange[0],
          activityDisc: disc,
          activityEndDatetime: timeRange[1],
          activityIsfree: ~~isFree,
          serveTime: (timeRange.map?.(res => toUtcTime(res)))?.join?.(),
          activityMoney: ~~isFree ? 0 : charge,
          activityName: name,
          communityId: communityId[communityId.length - 1],
          activityRecruitPeople: tmp,
          imagePath: cover,
          activityType: type,
          isleave: isCanLeave,
        },
        jobs: jobList,
      };
    },
    async toSubmit() {
      await this.$refs['form'].validate(async (valid) => {
        if (!valid) return null;
        const params = this.formatForm();
        const res = await this.$http.activityReleaseactivity(params);
        if (res.code !== 0) return null;
        this.$router.go(0);
      });
    },
    confirmLocation(location) {
      // 确认位置信息
      this.activity_add_params.address = JSON.stringify(location);
    },
    // 移除文件
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    async handleUpload(file) {
      const params = new FormData();
      params.append('files', file.file);
      const res = await this.$http.uploadFile(params);
      if (res.code !== 200) return this.$message.error(res.message);
      this.activity_add_params.cover = res.files[0];
    },
    async setJonDefault(id) {
      return await this.$http.jobList(id).then(
        (res) => {
          this.activity_add_params.jobList = res.data.map(({jobId, jobNumber, jobScore}) => {
            return {
              jobId,
              jobNumber,
              jobScore,
            };
          });
        },
      ).catch(e => {
        this.$message.warning('默认设置岗位失败');
      });
    },

    async handleSetDefault(info) {
      if (info.hasOwnProperty('isEdit')) {
        this.activity_add_params.name = info.activityName;
        this.activity_add_params.activityId = info.activityId;
        console.log(`info.activityId-->`, info.activityId);
        this.isEdit = true;
      }
      if (info.hasOwnProperty('activityId')) {
        this.activity_add_params.disc = info.activityDisc;
        this.activity_add_params.type = info.activityType;
        this.activity_add_params.charge = info.activityMoney;
        this.activity_add_params.cover = info.imagePath;
        this.option.isFree = info.activityIsfree;
        this.option.fileList.push({
          url: info.imagePath,
          uuid: moment().format(),
        });
        this.activity_add_params.isCanLeave = info.isleave;
        const id = info.activityId;
        await this.setJonDefault(id);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.icon-btn {

  position: relative;
  border: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  padding: 0 15px;
  font-size: 14px;
  height: 32px;
  line-height: 1;
  text-align: center;
  text-decoration: none;
  overflow: visible;
  margin-left: initial;
  transform: translate(0px, 0px);
  margin-right: initial;
}
</style>
